import React from 'react'
import Loadable from 'react-loadable'

// 通用转场(过渡)组件，函数组件
function LoadingComponent(props) {
  if (props.error) {
    // When the loader has errored
    return <div>Error! <button onClick={ props.retry }>Retry</button></div>;
  } else if (props.timedOut) {
    // When the loader has taken longer than the timeout
    return <div>Taking a long time... <button onClick={ props.retry }>Retry</button></div>;
  } else if (props.pastDelay) {
    // When the loader has taken longer than the delay
    return <div>Loading...</div>;
  } else {
    // When the loader has just started
    return null;
  }
}

// 定义 withLoadable 函数，用于将参数 loader 表示的组件动态加载进来
// loader: 需要动态加载的组件（是一个函数，返回 Promise，动态加载组件）
// loading: 转场组件，默认使用通用的转场组件
export const withLoadable = (loader, loading = LoadingComponent) => Loadable({
  loader,
  loading
})
